package com.sts.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sts.common.result.Result;
import com.sts.dto.UserRolesDTO;
import com.sts.dto.UserPageDTO;
import com.sts.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/users")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class UserController {
    private final UserService userService;
    //分页
    @GetMapping
    public Result<IPage<UserPageDTO>> page(@RequestParam(defaultValue = "1") long current,
                                           @RequestParam(defaultValue = "10") long size,
                                           @RequestParam(required = false) String keyword){
        return Result.success(userService.pageUser(new Page<>(current,size),keyword));
    }
    //修改用户的状态
    @PutMapping("/{id}/status")
    public Result<Void> toggleStatus(@PathVariable Long id,@RequestParam boolean enabled){
        userService.toggleUserStatus(id,enabled);
        return Result.success().message(enabled ? "用户已启用":"用户已禁用");
    }
    //更新用户的权限
    @PutMapping("/{id}/roles")
    public Result<Void> bindRoles(@PathVariable Long id, @Validated @RequestBody UserRolesDTO dto){
        dto.setUserId(id);
        userService.bindRole(dto);
        return Result.success().message("角色已更新");
    }
}
